package com.kui.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kui.entity.User;
import com.kui.util.DBHelp;
import com.kui.util.RowMapper;

public class UserDao {
	
	DBHelp<User> db = new DBHelp<User>();
	
	private class UserRowMapper implements RowMapper<User>{

		public User mapperRow(ResultSet rs) throws SQLException {
			User u = new User();
			u.setId(rs.getString("id"));
			u.setPassword(rs.getString("password"));
			u.setRole(rs.getString("role"));
			u.setUsername(rs.getString("username"));
			
			return u;
		}
		
	}

	public User findByNameAndPassword(String name, String password) {
		String sql = "SELECT id,username,`password`,role FROM t_user WHERE username = ? AND `password` = ?";
		return db.executeQueryForObject(sql, new UserRowMapper(), name,password);
	}

	public User findByName(String name) {
		String sql = "SELECT id,username,`password`,role FROM t_user WHERE username = ?";
		return db.executeQueryForObject(sql, new UserRowMapper(), name);
	}

	public void sign(User u) {
		String sql = "INSERT INTO t_user(id,username,`password`) VALUES(?,?,?)";
		db.executeSQL(sql, u.getId(),u.getUsername(),u.getPassword());
		
	}

	public void update(User u) {
		String sql = "UPDATE t_user SET password = ? where id = ?";
		db.executeSQL(sql, u.getPassword(),u.getId());
		
	}

	public List<User> findAll() {
		String sql = "SELECT id,username,`password`,role FROM t_user";
		return db.executeQueryForList(sql, new UserRowMapper());
	}

	public User findById(String uid) {
		String sql = "SELECT id,username,`password`,role FROM t_user WHERE id = ?";
		return db.executeQueryForObject(sql, new UserRowMapper(), uid);
	}

	public void updateRole(User u) {
		String sql = "UPDATE t_user SET role = ? where id = ?";
		db.executeSQL(sql, u.getRole(),u.getId());
		
	}

	public void del(User u) {
		String sql = "DELETE FROM t_user WHERE id = ?";
		db.executeSQL(sql, u.getId());
	}
	

}
